package com.lubase.metadata.tabletrigger;

import com.lubase.core.extend.IFormTrigger;
import com.lubase.core.model.CustomFormVO;
import com.lubase.core.util.ClientMacro;
import com.lubase.model.DbEntity;
import com.lubase.model.EDBEntityState;
import com.lubase.orm.QueryOption;
import com.lubase.orm.TableFilter;
import com.lubase.orm.exception.WarnCommonException;
import com.lubase.model.DbCollection;
import com.lubase.orm.operate.EOperateMode;
import com.lubase.orm.service.AppHolderService;
import com.lubase.orm.service.DataAccess;
import com.lubase.orm.util.TypeConverterUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatasourceInfoFormTrigger implements IFormTrigger {
    @Autowired
    DataAccess dataAccess;
    @Autowired
    AppHolderService appHolderService;

    @Override
    public String getTriggerTableCode() {
        return "ms_database";
    }

    @Override
    public String getDescription() {
        return "数据源维护表单触发器";
    }

    @Override
    public void initDefaultValue(DbEntity formDataEntity, ClientMacro clientMacro) {

    }

    @SneakyThrows
    @Override
    public void beforeLoadForm(CustomFormVO customFormVO, ClientMacro clientMacro) {
        // 判断权限：如果不是数据源管理员，无法维护数据源
        DbEntity data = customFormVO.getData();
        if (data.getDataState().equals(EDBEntityState.Modified)) {
            QueryOption queryOption = new QueryOption("ms_database");
            queryOption.setFixField("db_manager");
            queryOption.setTableFilter(new TableFilter("id", data.getId(), EOperateMode.Equals));
            DbCollection coll = dataAccess.queryAllData(queryOption);
            String dbManager = TypeConverterUtils.object2String(coll.getData().get(0).get("db_manager"), "");
            if (StringUtils.isEmpty(dbManager)) {
                throw new WarnCommonException("您无权限维护此数据源");
            }
            if (!dbManager.contains(appHolderService.getUser().getCode())) {
                throw new WarnCommonException("您无权限维护此数据源");
            }
        }
    }
}
